package br.com.appestoque.seguranca;

import javax.crypto.Cipher;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Criptografia {

	private static final String algoritmo = "AES";
	//private static final byte[] keyValue = null;
	
	private static final byte[] keyValue = new byte[] { '7', '8', '7', '2', '4', '2', '7', '@', '7', '6', '5', '4', '3', '2', '1', '0' };
	
	public Criptografia() {
	}

	public byte[] cifrar(String input) throws InvalidKeyException, BadPaddingException, 
													IllegalBlockSizeException, Exception {
	    KeyGenerator kgen = null;
		try {
			kgen = KeyGenerator.getInstance(algoritmo);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	    kgen.init(128);

	    SecretKeySpec skeySpec = new SecretKeySpec(keyValue,algoritmo);

	    Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(algoritmo);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}

	    try {
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}

	    byte[] cifrado = null;
		try {
			cifrado = cipher.doFinal(input.getBytes());
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		
		return cifrado;

	}

	public String decifrar(byte[] input) throws InvalidKeyException, BadPaddingException, 
	 															 IllegalBlockSizeException, Exception {
	    KeyGenerator kgen = null;
		try {
			kgen = KeyGenerator.getInstance(algoritmo);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	    kgen.init(128);

	    SecretKeySpec skeySpec = new SecretKeySpec(keyValue,algoritmo);

	    Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(algoritmo);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}

	    try {
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
	    byte[] decifrado = null;
		try {
			decifrado = cipher.doFinal(input);
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		
		return new String(decifrado);

	}
	
}